<template>
    <div v-if="state.isShow">
        <el-dialog
            v-model="state.isShow"
            title="编写事件"
            width="45%"
            :before-close="handleClose"
            center
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <code-mirror ref="codeMirrorRef" type="javascript" :read-only="false"/>
            <template #footer>
            <div class="footer">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="handleClose">关闭</el-button>
            </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import codeMirror from '@/components/code-mirror/index.vue'
import { reactive, ref ,nextTick} from 'vue';

const props = defineProps({
    selectWidget:{
        type:Object,
        default:()=>({}) 
    }
})

const state = reactive({
    isShow:false,
    eventName:''
})
const codeMirrorRef = ref()

const close = ()=>{
    state.isShow = false
}

const handleClose = ()=>{
    close()
}
const openDialog = (val,eventName)=>{
    state.isShow = true
    state.eventName = eventName 
    nextTick(()=>{
        if(val)
            codeMirrorRef.value.setValue(val)
    })
}

const save = ()=>{
    let js = codeMirrorRef.value.getValue() ?? ''

    /* 
        通过Function构造函数，将js字符串创建为函数，同时像函数内部传递一个名为value的参数
        new Function('value',js)()
    */
    handleClose()

    // 处理事件保存 将执行的代码作为字符串保存到当前事件名对应的字段中
    props.selectWidget.options[state.eventName] = js
}

defineExpose({
    openDialog
})
</script>

<style lang='scss' scoped></style>